#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
精简案例5-8代码中的display语句，减少一半
"""

import re
import os

def reduce_display_statements(file_path):
    """
    精简display语句的策略：
    1. 保留所有标题和分隔线（包含====或----的display）
    2. 保留所有步骤标题（第X步）
    3. 保留关键统计和结果
    4. 删除详细说明和冗余信息
    5. 合并连续的空display
    """
    
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    new_lines = []
    i = 0
    removed_count = 0
    total_display = 0
    
    while i < len(lines):
        line = lines[i]
        
        # 统计display语句
        if line.strip().startswith('display'):
            total_display += 1
        
        # 保留非display行
        if not line.strip().startswith('display'):
            new_lines.append(line)
            i += 1
            continue
        
        # 保留标题和分隔线
        if '====' in line or '----' in line:
            new_lines.append(line)
            i += 1
            continue
        
        # 保留步骤标题
        if re.search(r'第.+步', line) or re.search(r'Step \d+', line):
            new_lines.append(line)
            i += 1
            continue
        
        # 保留关键标记
        if any(marker in line for marker in ['【数据】', '【分析】', '【目标】', '【提示】', '【成就】', '【文档】', '【学习】', '【亮点】']):
            new_lines.append(line)
            i += 1
            continue
        
        # 保留完成标记
        if '完成' in line or '成功' in line or '✓' in line or '✅' in line:
            new_lines.append(line)
            i += 1
            continue
        
        # 保留日志和文件路径
        if '.log' in line or '.png' in line or '.gph' in line or 'output/' in line:
            new_lines.append(line)
            i += 1
            continue
        
        # 删除详细说明（以"   -"开头的行，表示子项）
        if line.strip().startswith('display "   -') or line.strip().startswith('display "     -'):
            removed_count += 1
            i += 1
            continue

        # 删除详细数字说明（包含具体数值的说明）
        if re.search(r'display ".+[:：].+\d+', line) and '第' not in line:
            # 但保留关键统计
            if any(key in line for key in ['R²', 'RMSE', 'MAE', '样本', '训练集', '测试集', '特征', '重要性', '模型性能']):
                new_lines.append(line)
            else:
                removed_count += 1
            i += 1
            continue

        # 删除图表列表（01. 02. 等）
        if re.search(r'display "\s+\d+\.', line) and '.png' in line:
            removed_count += 1
            i += 1
            continue

        # 删除图表分类标题（探索性分析、模型解释等）
        if any(cat in line for cat in ['探索性分析', '模型解释', '预测评估', '策略分析', '性能分析', '业务分析']):
            if '张' in line or '个' in line:  # 如"探索性分析（6张）"
                removed_count += 1
                i += 1
                continue
        
        # 删除策略详细说明（策略1、策略2等的详细内容）
        if re.search(r'display "策略\d+:', line):
            # 完全删除策略详细说明
            removed_count += 1
            i += 1
            # 跳过后续的详细说明
            while i < len(lines) and lines[i].strip().startswith('display "   '):
                removed_count += 1
                i += 1
            continue

        # 删除编号列表的详细内容（1. 2. 3.等）
        if re.search(r'display "\d+\.', line):
            # 检查是否是关键列表项
            if any(key in line for key in ['驱动因素', '关键', '重要', '核心']):
                new_lines.append(line)  # 保留关键列表项标题
                i += 1
                # 跳过后续的详细说明
                while i < len(lines) and lines[i].strip().startswith('display "   '):
                    removed_count += 1
                    i += 1
            else:
                # 完全删除非关键列表
                removed_count += 1
                i += 1
                # 跳过后续的详细说明
                while i < len(lines) and lines[i].strip().startswith('display "   '):
                    removed_count += 1
                    i += 1
            continue
        
        # 合并连续的空display
        if line.strip() == 'display ""':
            # 检查前一行是否也是空display
            if new_lines and new_lines[-1].strip() == 'display ""':
                removed_count += 1
                i += 1
                continue
            else:
                new_lines.append(line)
                i += 1
                continue
        
        # 默认保留其他display
        new_lines.append(line)
        i += 1
    
    # 写回文件
    with open(file_path, 'w', encoding='utf-8') as f:
        f.writelines(new_lines)
    
    return total_display, removed_count

def main():
    """处理案例5-8的do文件"""
    
    files = [
        'do/cases_by_chapter/part3_advanced/case05_pricing_strategy.do',
        'do/cases_by_chapter/part3_advanced/case06_supply_chain_optimization.do',
        'do/cases_by_chapter/part3_advanced/case07_performance_prediction.do',
        'do/cases_by_chapter/part4_comprehensive/case08_customer_lifetime_value.do'
    ]
    
    print("=" * 70)
    print("精简案例5-8的display语句")
    print("=" * 70)
    print()
    
    total_all = 0
    removed_all = 0
    
    for file_path in files:
        if not os.path.exists(file_path):
            print(f"⚠️  文件不存在: {file_path}")
            continue
        
        case_num = os.path.basename(file_path).split('_')[0].replace('case', '')
        print(f"处理案例{case_num}...")
        
        total, removed = reduce_display_statements(file_path)
        remaining = total - removed
        reduction_pct = (removed / total * 100) if total > 0 else 0
        
        print(f"  原始display语句: {total}个")
        print(f"  删除display语句: {removed}个")
        print(f"  保留display语句: {remaining}个")
        print(f"  精简比例: {reduction_pct:.1f}%")
        print()
        
        total_all += total
        removed_all += removed
    
    remaining_all = total_all - removed_all
    reduction_pct_all = (removed_all / total_all * 100) if total_all > 0 else 0
    
    print("=" * 70)
    print("总计")
    print("=" * 70)
    print(f"原始display语句总数: {total_all}个")
    print(f"删除display语句总数: {removed_all}个")
    print(f"保留display语句总数: {remaining_all}个")
    print(f"总体精简比例: {reduction_pct_all:.1f}%")
    print()
    print("✅ 精简完成！")
    print("=" * 70)

if __name__ == '__main__':
    main()

